package cn.ecasoft.pojo;

import cn.ecasoft.service.EnergyConsumptionService;
import cn.ecasoft.util.SpringUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.time.LocalDateTime;

import static cn.ecasoft.service.SocketHandler.*;

import static cn.ecasoft.service.SocketPool.*;

/**
 * @Author: LiangChun
 * @Description: socket包装
 * @DateTime: 2023/2/23
 **/
@Slf4j
@Data
@Component
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class ClientSocket implements Runnable {
    private Socket socket;
    private DataInputStream inputStream;
    private DataOutputStream outputStream;
    private String key;
    private String message;
    private Long currentLong;
    private Boolean isRemoved = false;
    private Integer timeout;

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
            try {
                if (!this.isRemoved) {
                    onMessage(this);
                    if (this.message != null) {
                        log.info(LocalDateTime.now() + " SocketKey:{}, 接收到数据:{} ", this.key, this.message);
                        sendMessage(this, SpringUtil.getBean(EnergyConsumptionService.class).handleCollectorRequest(this, this.message));
                    }
                } else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }
}
